import plugin from '../../lib/plugins/plugin.js'
import fetch from 'node-fetch'
import axios from 'axios'

const API = 'https://huai-huai-deepdanbooru-string.hf.space/api/predict'

let zt = 0

export class example extends plugin {
  constructor() {
    super({
            /** 功能名称 */
            name: '鉴赏图片',
            /** 功能描述 */
            dsc: '鉴赏图片',
            event: 'message',
            /** 优先级，数字越小等级越高 */
            priority: 1009,
            rule: [
                {
                    /** 命令正则匹配 */
                    reg: '^#?鉴赏$',
                    /** 执行方法 */
                    fnc: 'appreciate'
                }
            ]
        })
    }

  async appreciate(e) {
    if (API == '') return 
	if (zt == 1) {
		e.reply('当前有任务正在执行..', true)
		return
	}
	let image = await this.getImage(e)
	if (!image) return  
    
	let base64 = await url_to_base64(image)
    await e.reply('使用DeepDanbooru鉴赏中~（*/∇＼*）', true, { recallMsg: 10 })
	
	zt = 1
	let response = ""
	let res = ""
	
    try {
        response = await fetch(API, {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                data: [
                    "data:image/png;base64," + base64,
                    0.3,
                ]
            })
        })
        res = await response.json()
		
        let tags = res.data[2].confidences;
        let tags_str = '';
        for (let i = 0; i < tags.length; i++) {
            if (tags[i].confidence > 0.98) {
                tags_str += `(${tags[i].label}: 1.2), `;
            } else if (tags[i].confidence > 0.95 && tags[i].confidence < 0.98) {
                tags_str += `(${tags[i].label}: 1.1), `;
            } else if (tags[i].confidence > 0.9 && tags[i].confidence < 0.95) {
                tags_str += `(${tags[i].label}), `;
            } else {
                tags_str += `${tags[i].label}, `;
            }
        }

        await e.reply(tags_str, true)
		zt = 0
    } catch (err) {
        e.reply("鉴赏失败", true)
		zt = 0
    }
	
}
		
  async getImage(e) {
	let imgUrls = []
	  if (e.source || e.reply_id ) {
        // 优先从回复找图
        let reply
        if (this.e.getReply) {
          reply = await this.e.getReply()
        } else if (this.e.source) {
          if (this.e.group?.getChatHistory)
            reply = (await this.e.group.getChatHistory(this.e.source.seq, 1)).pop()
          else if (this.e.friend?.getChatHistory)
            reply = (await this.e.friend.getChatHistory(this.e.source.time, 1)).pop()
        }
        if (reply?.message) {
          for (let val of reply.message) {
            if (val.type === 'image') {
                imgUrls.push(val.url)
            }
          }
        }
      }
	  else if (e.img) {
        // 一起发的图
        imgUrls.push(...e.img)
      }   
	if (imgUrls.length) {
		logger.info(imgUrls)
        return imgUrls[0]
	} else {
		return ''
	}
  }
}

async function url_to_base64(url) {
        let img = await axios.get(url, {
            responseType: 'arraybuffer'
        });
        let base64 = Buffer.from(img.data, 'binary')
            .toString('base64');
        return base64
    }